// src/main/java/com/bookmanager/controller/BookManagementController.java
package com.bookmanager.controller;

import com.bookmanager.model.Book;
import com.bookmanager.model.User;
import com.bookmanager.service.BookService;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import java.io.IOException;
import java.util.List;

@WebServlet("/admin/book-management")
public class BookManagementController extends HttpServlet {
    private BookService bookService = new BookService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");

        // 检查管理员权限
        if (user == null || !"admin".equals(user.getRole())) {
            response.sendRedirect("../login.jsp");
            return;
        }

        String action = request.getParameter("action");
        List<Book> books;

        if ("search".equals(action)) {
            String keyword = request.getParameter("keyword");
            books = bookService.searchBooks(keyword);
            request.setAttribute("keyword", keyword);
        } else {
            books = bookService.getAllBooks();
        }

        // 如果数据库没有数据，使用模拟数据
        if (books == null || books.isEmpty()) {
            books = createSampleBooks();
        }

        request.setAttribute("books", books);
        request.getRequestDispatcher("/admin/book-management.jsp").forward(request, response);
    }

    private List<Book> createSampleBooks() {
        // 使用您之前在 BookController 中的示例数据
        List<Book> books = new java.util.ArrayList<>();

        Book book1 = new Book();
        book1.setBookId(1);
        book1.setIsbn("9787111126768");
        book1.setTitle("Java编程思想");
        book1.setAuthor("Bruce Eckel");
        book1.setPublisher("机械工业出版社");
        book1.setPrice(new java.math.BigDecimal("89.00"));
        book1.setCategory("计算机");
        book1.setTotalCopies(5);
        book1.setAvailableCopies(3);
        book1.setStatus("available");
        books.add(book1);

        Book book2 = new Book();
        book2.setBookId(2);
        book2.setIsbn("9787115216878");
        book2.setTitle("Spring实战");
        book2.setAuthor("Craig Walls");
        book2.setPublisher("人民邮电出版社");
        book2.setPrice(new java.math.BigDecimal("79.00"));
        book2.setCategory("计算机");
        book2.setTotalCopies(3);
        book2.setAvailableCopies(0);
        book2.setStatus("borrowed");
        books.add(book2);

        return books;
    }
}